package com.lagou.sqlsession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... param) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        Executor executor = new SimpleExecutor();
        List<Object> list = executor.query(configuration, mappedStatement, param);
        return (List<E>) list;
    }

    @Override
    public <E> E selectOne(String statementId, Object... param) throws Exception {
        List<Object> objects = this.selectList(statementId, param);
        if (objects.size() == 1) {
            return (E) objects.get(0);
        } else {
            throw new RuntimeException("返回结果为零或过多");
        }
    }

    @Override
    public Boolean update(String statementId, Object... param) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        Executor executor = new SimpleExecutor();
        return executor.update(configuration, mappedStatement, param);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        String className = method.getDeclaringClass().getName();
                        String methodName = method.getName();
                        String statementId = className + "." + methodName;
                        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);

                        switch (mappedStatement.getMethodType()) {
                            case "select":
                                Type genericReturnType = method.getGenericReturnType();
                                if (genericReturnType instanceof ParameterizedType)
                                    return selectList(statementId, args);
                                return selectOne(statementId, args);
                            case "update":
                                return update(statementId, args);
                            case "delete":
                                return update(statementId, args);
                            default:
                                throw new RuntimeException("不识别的方法");
                        }
                    }
                });
        return (T) proxyInstance;
    }
}
